package wangxiaotao.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import wangxiaotao.utils.NoUtils;

import java.time.LocalDateTime;

@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());//防止全表删除
        return interceptor;
    }

    @Component
    public static class MyMetaObjectHandle implements MetaObjectHandler {
        //自定义自动更新插入数据
        @Override
        public void insertFill(MetaObject metaObject) {
            //创建时间
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            //订单编号
            this.strictInsertFill(metaObject, "orderNo", String.class, NoUtils.setOrderNo());
            //逻辑删除
            this.strictInsertFill(metaObject, "isDeleted", Boolean.class, true);
        }
        @Override
        public void updateFill(MetaObject metaObject) {
            //更新时间
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }
    //将插件加入到mybatis插件拦截链中
//    @Bean
//    public ConfigurationCustomizer configurationCustomizer() {
//        return configuration -> {
//            //插件拦截链采用了责任链模式，执行顺序和加入连接链的顺序有关
//            MyPluginInterceptor myPlugin = new MyPluginInterceptor();
//            //设置参数，比如阈值等，可以在配置文件中配置，
//                Properties properties = new Properties();
//                //这里设置慢查询阈值为1毫秒，便于测试
//                properties.setProperty("time", "1");
//                myPlugin.setProperties(properties);
//            configuration.addInterceptor(myPlugin);
//        };
//    }
}
